package com.example.pt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.entity.User;
import com.example.pt.entity.UserLevel;
import com.example.pt.service.UserLevelService;
import com.example.pt.service.UserService;
import com.example.pt.task.UserLevelUpdateTask;
import com.example.pt.utils.DownloadUrlUtils;
import com.example.pt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户等级控制器
 */
@RestController
@RequestMapping("/api/user/level")
@CrossOrigin(origins = "*")
public class UserLevelController {
    
    @Autowired
    private UserLevelService userLevelService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserLevelUpdateTask userLevelUpdateTask;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;
    
    /**
     * 获取用户当前等级和积分
     * @return 用户等级信息
     */
    @GetMapping
    public ResponseEntity<?> getUserLevelInfo(@RequestHeader Map<String, String> headers) {
        String token = headers.get("token");
        if (token == null) {
            token = headers.get("authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        }
        
        if (token == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: 缺少token");
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        
        try {
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 根据当前积分计算用户等级，但不更新数据库
            UserLevel level = UserLevel.getLevelByPoints(user.getPoints());
            
            Map<String, Object> response = new HashMap<>();
            response.put("userId", userId);
            response.put("username", user.getUsername());
            response.put("points", user.getPoints());
            response.put("level", level.getId());
            response.put("levelName", level.getName());
            response.put("minPoints", level.getMinPoints());
            response.put("maxPoints", level.getMaxPoints());
            response.put("canExchangeInvitation", level.canExchangeInvitation());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: " + e.getMessage());
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 手动更新用户等级
     * @param userId 用户ID
     * @return 更新后的等级信息
     */
    @PostMapping("/update/{userId}")
    public ResponseEntity<?> updateUserLevel(@PathVariable Integer userId) {
        if (userId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }
        
        User user = userService.searchByUid(userId);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 计算并更新等级
        UserLevel level = userLevelService.updateUserLevel(userId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("userId", userId);
        response.put("username", user.getUsername());
        response.put("points", user.getPoints());
        response.put("level", level.getId());
        response.put("levelName", level.getName());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 手动触发所有用户等级更新
     * 仅管理员可用
     * @return 更新结果
     */
    @PostMapping("/update-all")
    public ResponseEntity<?> updateAllUserLevels() {
        try {
            // 调用定时任务中的方法执行所有用户等级更新
            userLevelUpdateTask.updateAllUserLevels();
            return ResponseEntity.ok("所有用户等级更新任务已触发");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新所有用户等级失败: " + e.getMessage());
        }
    }
    
    /**
     * 兑换邀请码
     * @return 兑换结果
     */
    @PostMapping("/exchange-invitation")
    public ResponseEntity<?> exchangeInvitationCode(@RequestHeader Map<String, String> headers) {
        String token = headers.get("token");
        if (token == null) {
            token = headers.get("authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        }
        
        if (token == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: 缺少token");
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        
        try {
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 尝试兑换邀请码
            String invitationCode = userLevelService.exchangeInvitationCode(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("userId", userId);
            response.put("invitationCode", invitationCode);
            response.put("points", user.getPoints());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", e.getMessage());
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 使用邀请码
     * @param userId 用户ID
     * @param invitationCode 邀请码
     * @return 使用结果
     */
    @PostMapping("/use-invitation")
    public ResponseEntity<?> useInvitationCode(@RequestParam Integer userId, @RequestParam String invitationCode) {
        if (userId == null || invitationCode == null || invitationCode.isEmpty()) {
            return ResponseEntity.badRequest().body("用户ID和邀请码不能为空");
        }
        
        boolean success = userLevelService.rewardNewUserWithInvitation(userId, invitationCode);
        
        if (success) {
            return ResponseEntity.ok("邀请码使用成功");
        } else {
            return ResponseEntity.badRequest().body("邀请码无效或已使用");
        }
    }

    @GetMapping("/integral")
    public Map<String, String> getIntegral() {

        String integralDownloadLink = downloadUrlUtils.generateIntegralDownloadLink();
        if(integralDownloadLink != null) {
            Map<String, String> response = new HashMap<>();
            response.put("integralDownloadLink", integralDownloadLink);
            return response;
        }
        Map<String, String> response = new HashMap<>();
        response.put("message", "fail");
        return response;
    }
} 